<template>
  <div>
    <input type="text" v-model.trim="keyword" @keyup.enter="handleEnter" />
    <h2>列表渲染</h2>
    <ul>
      <li
        v-for="(item, index) of list"
        :class="[index % 2 == 0 ? 'bg-green' : 'bg-red']"
        :key="item"
      >
        {{ item }} <button @click="delItem(item)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from "vue";
let keyword = ref("");
let list = ref([]);
/* 1、回车事件获取输入框的值 */
const handleEnter = () => {
  /* keyword的值是true同时 list中没有keyword */
  if (keyword.value && !list.value.includes(keyword.value)) {
    list.value.push(keyword.value);
    keyword.value = "";
  } else {
    alert("值重复&值为空");
  }
};
/* 2、处理删除 */
const delItem = (item) => {
  /* 2-1、findIndex+splice */
  // var index = list.value.findIndex((val) => val == item);
  // list.value.splice(index, 1);
  /* 2-2、filter */
  var res = window.confirm("确实删除吗?");
  console.log(res);
  if (res) {
    var arr = list.value.filter((val) => val != item);
    list.value = arr;
  }
};
</script>

<style scoped>
.bg-green {
  background-color: green;
}
.bg-red {
  background-color: red;
}
</style>
